# -*- coding: utf-8 -*-
# @Author	: starview.guojian.ma
# @Date		: 2022/5/23 15:22
# @Last Modified by:   starview.guojian.ma
# @Last Modified time: 2022/5/23 15:22
# Thanks for your comments!

import logging
from motor.motor_asyncio import AsyncIOMotorClient

logger = logging.getLogger(__name__)


def init_mongo(config):
    try:
        if config['username'] and config['password']:
            client = AsyncIOMotorClient(host=config['host'],
                                        port=config['port'],
                                        username=config['username'],
                                        password=config['password'],
                                        authSource=config['database'],
                                        authMechanism="SCRAM-SHA-1",
                                        serverSelectionTimeoutMS=50000,
                                        socketTimeoutMS=50000)
        else:
            client = AsyncIOMotorClient(host=config['host'],
                                        port=config['port'],
                                        serverSelectionTimeoutMS=50000,
                                        socketTimeoutMS=50000)
    except Exception as e:
        logger.error(f"mongodb initialized failed with err:{str(e)}")
        return None

    logger.info(f"mongodb initialized success. host:{config['host']}, port:{config['port']}")
    return client[config.get('database', 'test')]
